import _thread
import os
import threading
import time
from multiprocessing import Process
import asyncio

def get_now_time():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())


def print_time(thread_name: str, number_time: int, delay: int):
    for i in range(number_time):
        print(f"{thread_name}: {get_now_time()}")
        time.sleep(delay)


# _thread.start_new_thread(print_time, ("Thread-1", 2, 1))
# _thread.start_new_thread(print_time, ("Thread-2", 2, 2))
#
# # 以防主线程结束
# input()
# print("主线程结束")

# t1 = threading.Thread(target=print_time, args=("Thread-1", 2, 1))
# t2 = threading.Thread(target=print_time, args=("Thread-2", 2, 2))
#
# t1.start()
# t2.start()


# def add():
#     sum = 0
#     for i in range(1, 100000):
#         sum += i
#     print(sum)
#
#
# def mul():
#     sum2 = 1
#     for i in range(1, 100000):
#         sum2 = sum2 * i
#     print(sum2)
#
#
# start_time = time.time()
#
# add()
# mul()
#
# print(f"cost {time.time() - start_time}s")


class PrintThread(threading.Thread):

    def __init__(self, thread_name, number_time, delay):
        super().__init__(name=thread_name, target=print_time, args=(number_time, delay))
        self.thread_name = thread_name
        self.number_time = number_time
        self.delay = delay

    def run(self):
        for i in range(self.number_time):
            print(f"{self.thread_name}: {get_now_time()}")
            time.sleep(self.delay)

#
# t1 = PrintThread("thread 1", 2, 1)
# t2 = PrintThread("thread 2", 10, 10)
# t1.start()
# t2.setDaemon(True)
# t2.start()
# time.sleep(1)
# print("end")

# 实例化一个multiprocessing.Process的对象
# subproc1 = Process(target=print_time, args=("Process-1", 2, 1))
# subproc2 = Process(target=print_time, args=("Process-2", 2, 1))
#
# subproc1.start()
# subproc2.start()


class PrintProcess(Process):

    def __init__(self, process_name, number_time, delay):
        super().__init__(name=process_name, target=print_time, args=(number_time, delay))
        self.process_name = process_name
        self.number_time = number_time
        self.delay = delay

    def run(self):
        for i in range(self.number_time):
            print(f"{self.process_name}: {get_now_time()}")
            time.sleep(self.delay)


async def hello():
    print("hello")
    # await asyncio.sleep(1)
    print("world")


async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)


async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")


async def main():
    task1 = asyncio.create_task(say_after(1, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")


async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({i})...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")


async def main():
    await asyncio.gather(
        say_after(1, 'hello'),
        say_after(2, 'world')
    )

# asyncio.wait_for(aw, timeout, *, loop=None)
async def eternity():
    await asyncio.sleep(3600)
    print('yay!')


async def main():
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError:
        print('timeout!')

# asyncio.run(main())


async def say_hello():
    aws = (say_after(1, 'hello'), say_after(2, 'world'))
    for f in asyncio.as_completed(aws):
        await f


async def foo():
    print(get_now_time())


async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(say_hello())
    await asyncio.wait({task2, task1}, return_when=asyncio.ALL_COMPLETED)

asyncio.run(main())



